package com.xing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.DTO.RoleMenuSaveDTO;
import com.xing.Utils.Result;
import com.xing.dao.SysRoleMenuDao;
import com.xing.entity.SysRoleMenuEntity;
import com.xing.service.SysRoleMenuService;
import com.xing.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenuEntity> implements SysRoleMenuService {

    @Autowired
    private SysRoleMenuDao roleMenuDao;


    @Override
    public List<Long> getMenuIdByRoleId(Long roleId) {
        return roleMenuDao.getMenuIdByRoleId(roleId);
    }


    @Override
    @Transactional
    public Result saveUserRoleRelation(RoleMenuSaveDTO roleMenuSaveDTO) {
        // 获取角色id判断是否可用
        Long roleId = roleMenuSaveDTO.getRoleId();
        if (roleId == null) {
            return new Result().err(406, "缺少角色id");
        }
        // 删除角色原有权限
        LambdaQueryWrapper<SysRoleMenuEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(SysRoleMenuEntity.class)
                .eq(SysRoleMenuEntity::getRoleId, roleId);
        roleMenuDao.delete(lambdaQueryWrapper);
        List<SysRoleMenuEntity> menuEntityList = roleMenuSaveDTO.getRoleMenuEntityList();
        if (!menuEntityList.isEmpty()) {
            // 批量插入权限信息
            boolean saveBatch = this.saveBatch(menuEntityList);
            // 返回操作结果
            if (saveBatch) {
                return new Result().ok("更新成功");
            }
            return new Result().err(407, "更新失败");
        }
        return new Result().ok("更新成功");
    }


}
